package com.dyit.controllor;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dyit.config.AliPayConfig;
import com.dyit.entity.Order;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import static com.alipay.api.AlipayConstants.APP_ID;

@RestController
@RequestMapping("/api/alipay")
public class Pay {
    @RequestMapping("/pay")
    public void aliPay(Integer orderId, HttpServletResponse httpResponse) throws Exception{
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AliPayConfig.return_url);
        request.setNotifyUrl(AliPayConfig.notify_url);
        //根据订单编号,查询订单相关信息
        Order order = new Order("111", "222", "333");
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrder_code();
        //付款金额，必填
        String total_amount = order.getOrder_price();
        //订单名称，必填
        String subject = order.getName();
        //商品描述，可空
        String body = "";

        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (
                AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AliPayConfig.charset);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}
